<?php
namespace WXAPI\Controller;
use Think\Controller;
use Think\Exception;
use WXAPI\Logic\GoodsLogic;
use Think\Page;
use WXAPI\Logic\CartLogic;
class CartController extends BaseController
{
    public $cartLogic; // 购物车逻辑操作类

    public function cs()
    {
        $order = M('order')->where(['order_sn'=>'202503201131121898'])->select();
        $res = $this->getWXPayInfo($order);
        print_r($res);exit;
    }

    /**
     * 析构流函数
     */
    public function  __construct()
    {
        parent::__construct();
        $this->cartLogic = new CartLogic();
        $user_id = I("user_id",0); // 用户id
        // 给用户计算会员价 登录前后不一样
        // if ($user_id) {
        //     $user = M('users')->where("user_id = {$user_id}")->find();
        //     M('Cart')->execute("update `__PREFIX__cart` set member_goods_price = goods_price * {$user['discount']} where user_id = {$user_id}  and  prom_type = 0");
        // }

    }

    /**
     * 将商品加入购物车
     */
    function addCart()
    {
        $goods_id = I("goods_id"); // 商品id
        $goods_num = I("goods_num");// 商品数量
        $goods_spec = I("goods_spec"); // 商品规格
        $ms_id = I("ms_id"); // 秒杀id
        $is_pint = I('is_pint',0);
        $pint_id = I('pint_id',0);
        $this->user_id = I('user_id');
        
        if($goods_spec!="")
            $goods_spec = explode('_',$goods_spec); 
        else 
        	$goods_spec = null;
        //$goods_spec = json_decode($goods_spec, true); //app 端 json 形式传输过来
        $unique_id = I("session_id"); // 唯一id  类似于 pc 端的session id
        //$user_id = I("user_id",0); // 用户id shadow

        $count = M('cart')->where(['user_id'=>$this->user_id])->count();
        if($count >= 100){
            exit(json_encode(array('status'=>-4,'msg'=>'购物车数量已经超出限制','result'=>'')));
        }

        $result = $this->cartLogic->addCart($goods_id, $goods_num, $goods_spec, $unique_id, $this->user_id, $ms_id, $is_pint, $pint_id); // 将商品加入购物车
        
        exit(json_encode($result));
    }
	
    //清空购物车
    public function emptyCart() {
        $this->user_id = I('user_id');
        $unique_id = I('session_id');
        $res = M("Cart")->where(array("session_id"=>$unique_id, 'user_id'=>$this->user_id))->delete();
        $res = M("Cart")->where(array("session_id"=>$unique_id))->delete();
        $res = M("Cart")->where(array('user_id'=>$this->user_id))->delete();
    }

    public function updateNum()
    {
        $id = I("id"); 
        $num = I('num');
        $cart = M('Cart')->where(['id'=>$id])->find();
        $max_num = 0;
        $spec_key = '';
        if(!empty($cart['prom_id'])){
            $prom = M('prom_goods')->where(['id'=>$cart['prom_id']])->find();
            if(!empty($prom)){
                $max_num = $prom['xiangou'];
                $goodskey = json_decode($prom['goods_key'],true);
                if(in_array($cart['spec_key'],$goodskey)){
                    if($max_num!=0){
                        if($num > $max_num){
                            M('Cart')->where(['id'=>$id])->save(array("goods_num"=>$max_num));
                            // throw new \Exception('超过了最大限购');
                            $return_arr = array('status' => -1, 'msg' => '超过了最大限购', 'result' => ''); // 返回结果状态
                            exit(json_encode($return_arr));
                        }
                    }
                }
            }
        }
        
        $res = M('Cart')->where(array("id"=>$id))->save(array("goods_num"=>$num)); 
        $return_arr = array('status' => 1, 'msg' => '成功', 'result' => 0); // 返回结果状态
        exit(json_encode($return_arr));
    }
    
    public function updateSelect()
    {
        $id = I("id");
        $selected = I('selected');
        $res = M('Cart')->where(array("id"=>$id))->save(array("selected"=>$selected));
        $return_arr = array('status' => 1, 'msg' => '成功', 'result' => 0); // 返回结果状态
        exit(json_encode($return_arr));
    }

    public function updateAllSelect()
    {
        $session_id = I("open_id");
        $selected = I('selected');
        $user_id = 0;
        $user = [];
        if(!empty($session_id)){
            $user = M('users')->where(['open_id'=>$session_id])->find();
        }
        $selected = I('selected');
        $res = M('Cart')->where('session_id = "'.$session_id.'" or user_id='.$user['user_id'])->select();
        foreach ($res as $value)
        {
            $res = M('Cart')->where(array("id"=>$value['id']))->save(array("selected"=>$selected));
        }
        
        $return_arr = array('status' => 1, 'msg' => '成功', 'result' => 0); // 返回结果状态
        exit(json_encode($return_arr));
    }
	
    /**
     * 删除购物车的商品
     */
    public function delCart()
    {
        $id = I("id"); // 商品 ids        
        $result = M("Cart")->where(array("id"=>$id))->delete(); // 删除id为5的用户数据

        // 查找购物车数量
        //$unique_id = I("uid"); // 唯一id  类似于 pc 端的session id
        //$cart_count = cart_goods_num($unique_id);
        $return_arr = array('status' => 1, 'msg' => '删除成功', 'result' => 0); // 返回结果状态
        exit(json_encode($return_arr));
    }


    /*
     * 请求获取购物车列表
     */
	 
    public function cartList_cs(){
		//$cart_form_data = $_POST["cart_form_data"]; // goods_num 购物车商品数量
     //$cart_form_data = json_decode($cart_form_data, true); //app 端 json 形式传输过来
 
     $unique_id = I("session_id"); // 唯一id  类似于 pc 端的session id
     $this->user_id = I("user_id",0); // 用户id
     $where = " "; // 默认按照 $unique_id 查询
     $this->user_id && $where = $where ." user_id = " . $this->user_id; // 如果这个用户已经等了则按照用户id查询
     //修改购物车商品重复不会自动合并
       $cart = M('Cart')->field('goods_id,spec_key,store_id,member_goods_price,prom_id')->where($where)->select();
    foreach ($cart as $k=>$v){
        $cartCount = M('Cart')->where($where)->where(['spec_key'=>$v['spec_key']])->count();
        if($cartCount >= 2){//有重复的进来合并
            $cartData = M('Cart')->where($where)->where(['spec_key'=>$v['spec_key']])->find();//原始数据
            $cartSum = M('Cart')->where($where)->where(['spec_key'=>$v['spec_key'],'id'=>['neq',$cartData['id']]])->sum('goods_num');//计算出其余数量
            M('Cart')->where($where)->where(['spec_key'=>$v['spec_key'],'id'=>['neq',$cartData['id']]])->delete();//删除原始数据以外的所有数据
            M('Cart')->where(['id'=>$cartData['id']])->setField(['goods_num'=>$cartData['goods_num']+$cartSum]);
        }
    }
     $mycart_list = M('Cart')->field('id,goods_id,spec_key,store_id,member_goods_price,prom_id,goods_num')->where($where)->select(); //实时更新购物车
    $discount = 1;
    if ($this->user_id != 61) {
        $user = M('users')->where("user_id = {$this->user_id}")->cache(true,TPSHOP_CACHE_TIME)->find();
		$discount=$user['discount'];
    }

 	foreach($mycart_list as $v){
 		$new_price=get_goods_huodong($v['goods_id'],$v['spec_key'],$this->fenbu_id); //活动价格
 		$new_price['price'] = $discount*$new_price['price'];
        $float = check_float($v['store_id'],$this->user_id);
        $new_price['price'] = sanwei($new_price['price'] + ($new_price['price']*($float/100)));

//  		dump($new_price);
 		$quyu_price=quyu_price($this->fenbu_id,$v['store_id']); //区域价格
//  		dump($quyu_price);
 		$goods_id = $v['goods_id'];
        $spec = $v['spec_key'];
        $goods_num = $v['goods_num'];
        // dump($goods_num);
        if(!empty($goods_id)){
                $goodsData = M('goods')->where(['goods_id'=>$goods_id])->find();
                if(!empty($goodsData)){
                    //获取活动id
                    if($goodsData['prom_id'] != 0){
                        $promGoods = M('prom_goods')->where(['id'=>$goodsData['prom_id']])->find();
                        // $aa = $promGoods;
                        $time = time();
                        //活动存在而且开始了
                        if($promGoods['start_time'] < $time && $promGoods['end_time'] >$time){//活动期间
                            $promSpec = json_decode($promGoods['goods_key'],true);
                                if(in_array($spec,$promSpec) && $goods_num >=$promGoods['xiangou'] && $promGoods['xiangou'] !=0){
                                   $goods_num = $promGoods['xiangou'];
                                }

                        }
                    }else{ //少于起订的默认数量变起订
                        $specGoodsPrice = M('spec_goods_price')->where(['goods_id'=>$v['goods_id'],'key'=>$v['spec_key']])->find();
                        if($v['goods_num'] < $specGoodsPrice['qipi_num']){
                            $goods_num = $specGoodsPrice['qipi_num'];
                        }
                    }
                }
            }
            $yijia = 0;
            if($goodsData['stop_yijia'] == 1){
                $yijia = yj_price($v['goods_id'],sanwei($new_price["price"])*$quyu_price,$this->fenbu_id);
            }
 			M('cart')->where('id='.$v['id'])->save([
 				'spec_key_name'=>$new_price["key_name"],
 				'goods_price'=>sanwei($new_price["price"])*$quyu_price,
 				'member_goods_price'=>sanwei($new_price["price"])*$quyu_price,
				'yijia'=>$yijia,
 				'prom_msg'=>$new_price["prom_msg"],
 				'prom_id'=>$new_price["prom_id"],
 				'goods_num'=>$goods_num,
 				'goods_name'=>$goodsData['goods_name'],
 			]);
 	}

 
     $cartList=M('Cart')->field('store_id')->where($where)->group('store_id')->select();
 	
 	foreach($cartList as $k=>$v){
		
		$store_stop=M('store')->where('store_id='.$v['store_id'])->getField('quyu_stop'); //店铺区域屏蔽
		if(strpos($store_stop,$this->fenbu_id) !== false){
			M('Cart')->where('store_id='.$v['store_id'].' and user_id ='.$this->user_id)->delete();
			unset($cartList[$k]);
			continue;
		}

     $goods_list = M('Cart a')
 	->field('a.id,b.stop_yijia,a.goods_id,a.goods_name,a.spec_key_name,a.spec_key,a.prom_msg,a.member_goods_price,a.goods_num,a.selected,a.store_id,b.original_img,b.is_on_sale,b.is_delete,b.goods_state,a.add_time')
 	->join('ty_goods b on a.goods_id=b.goods_id')
 	->where(array('a.store_id'=>$v['store_id']))
 	->order('id desc')
 	->where($where)
 	->select();
    $cartAddTime = 0;
     foreach ($goods_list as $key => $value)
     {
         //$goods_list[$key] = array_merge(M('goods')->where(array("goods_id"=>$value['goods_id']))->find(),$value);
 		$goods_list[$key]['prom_msg'] = $value['prom_msg'] ? $value['prom_msg'] : '';
        $goods_list[$key]['image'] = C('MYOSS')['url'].$goods_list[$key]['original_img'];
 		$goods_list[$key]['minnum'] = M('spec_goods_price')->where(array("key"=>$value['spec_key'],"goods_id"=>$value['goods_id']))->getField('qipi_num');
        if($value['stop_yijia'] == 1){
            $goods_list[$key]['member_goods_price']+=yj_price($value['goods_id'],$value['member_goods_price'],$this->fenbu_id);
        }

 		$goods_list[$key]['xiaoji'] = \sanwei($goods_list[$key]['member_goods_price']*$value['goods_num']);
 		
 		if($this->user_id=='61'){
 		$goods_list[$key]['xiaoji']='登陆查看'; //浮点计算
 		$goods_list[$key]['member_goods_price']='登陆查看'; //浮点计算
 		}else{
            $goods_list[$key]['member_goods_price'] = sanwei($goods_list[$key]['member_goods_price']);
            $goods_list[$key]['xiaoji'] = sanwei($goods_list[$key]['xiaoji']);
        }
 		
 		if($value['is_on_sale']==0 || $value['is_delete']==1 || $value['goods_state']!=1){
 			M('Cart')->where('id='.$value['id'])->delete();
 			unset($goods_list[$key]);
 		}
         if($this->user_id){
             M('cart')->where(array("id"=>$value['id']))->save(array("user_id"=>$this->user_id));
         }
 	    if($cartAddTime < $value['add_time']){
            $cartAddTime = $value['add_time'];
        }
     }
 	$cartList[$k]['cartAddTime'] = $cartAddTime;
 	$cartList[$k]['store_name'] = M('store')->where(array("store_id"=>$v['store_id']))->getField('store_name');
 	$cartList[$k]['goods_list'] =$goods_list;
 	if(empty($goods_list))
 		unset($cartList[$k]);
 	
 	}
 	usort($cartList, function($a, $b) {
            return $b['cartAddTime'] - $a['cartAddTime']; // 正序排序
        });
 	//20181110  判断是否启用多店铺 便于审核  jun
 	$basic=tpCache("basic");
 	$is_show_store=$basic['app_test'];
 	//20181110  判断是否启用多店铺 便于审核  jun
//  	sort($cartList);
     $result = $cartList;
 
 	 exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$result,'is_show_store'=>$is_show_store)));
 }

    /**
     * 购物车第二步确定页面
     */
    public function cart2()
    {
    	$this->user_id = I('user_id');
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        //$user_id = I("user_id"); // 用户id
        $usersInfo = get_user_info($this->user_id);  // 用户
		$usersInfo['pay_points']=0; //shadow 限制积分显示
        $basic=tpCache("basic");

        $spec_key  = I('spec_key','');

        if($spec_key){
            $spec_key = " and a.spec_key = '".$spec_key."' ";
        }

        if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));
        if ($this->cartLogic->cart_count($this->user_id, 1) == 0) exit(json_encode(array('status' => -2, 'msg' => '你的购物车没有选中商品', 'result' => '')));

        // 购物车商品
        $cart_result = $this->cartLogic->cartList($usersInfo, $unique_id, 1, 1,$spec_key); // 获取购物车商品
        // 没有选中的不传递过去
        $cartList = array();
        $store_id_arr = [];
        $store_id = 0;
        $store_id_arr[] = $store_id;
        $is_public_where = ''; //默认优惠券和活动共用
        foreach ($cart_result['cartList'] as $key => $val) {
            if ($val['selected'] == 1)
            {
            	if($val['store_id'] != $store_id){
            		$val['show'] = 1;
            		$store_id = $val['store_id'];
            		$store_id_arr[] = $store_id;
            	}
                $cartList[] = $val;
            }
        }
        foreach ($cart_result['cartList'] as $key => $val) {
            if($val['prom_id'] > 0){
                $is_public_where = 'is_public = 1 and';
                break;
            }
        }
        $goods_ids = [];
        $store_arr = [];
        foreach ($cartList as $key => $value)
        {
            //$goodsData = array_merge(M('goods')->where(array("goods_id"=>$value['goods_id']))->find(),$value);
        	//$cartList[$key] = $goodsData;
        	$cartList[$key]['image'] = C('MYOSS')['url'].$cartList[$key]['original_img'];
        	$cartList[$key]['store_name'] = M('store')->where(array("store_id"=>$value['store_id']))->getField('store_name');
			$cartList[$key]['prom_msg'] = $value['prom_msg'] ? $value['prom_msg'] : '';
        	//组装数据，方便计算运费 BY 维亚轩 Mrlu 20180411
			if($value['is_free_shipping'] == 1){
				$orderGoods[$value['goods_id']]['weight'] = 0;
			}else{
				$orderGoods[$value['goods_id']]['weight'] = $value['weight']*$value['goods_num'];
			}
            $yijia = 0;
			if($value['stop_yijia'] == 1){
                $yijia=yj_price($value['goods_id'],$cartList[$key]['member_goods_price'],$this->fenbu_id);
            }


            $cartList[$key]['member_goods_price']+=$yijia;
			
			$cartList[$key]['goods_price']+=$yijia;
			$cartList[$key]['shop_price']+=$yijia;

            $cartList[$key]['member_goods_price'] = sanwei($cartList[$key]['member_goods_price']);
            $cartList[$key]['goods_price'] = sanwei($cartList[$key]['goods_price']);
            $cartList[$key]['shop_price'] = sanwei($cartList[$key]['shop_price']);

            $orderGoods[$value['goods_id']]['goods_num'] = $value['goods_num'];
            $orderGoods[$value['goods_id']]['store_id'] = $value['store_id'];
            $orderGoods[$value['goods_id']]['shop_price'] = sanwei($cartList[$key]['member_goods_price']*$value['goods_num']);
            $goods_ids[]=$value['goods_id'];
            if(!in_array($value['store_id'],$store_arr)){
                array_push($store_arr,$value['store_id']);
            }
        }
        
        $cart_result['cartList'] = $cartList;
        // 物流公司 

        $paymentList = M('Plugin')->where("`type` = 'payment' and status = 1 and code = 'cod' ")->select();// 支付方式
        // dump($paymentList);
        // if($testStore == 0){
        // 	$paymentList=array($paymentList[1]);
        // }
        //sofwu
//        if($basic['is_pays']==0){
//            unset($paymentList[1]);
//        }
        $paymentList = array_values($paymentList);
        // dump($paymentList);
        // 优惠券
        $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的     
        
        $sql = "select c1.name,c1.brand_id,c1.money,c1.condition,c1.use_start_time,c1.use_end_time,c1.goods_ids, c2.* from __PREFIX__coupon as c1 inner join __PREFIX__coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,4,5) and order_id = 0
        where c2.uid = {$this->user_id}  and ".time()." < c1.use_end_time and c1.condition <= {$cart_result['total_price']['total_fee']} and c2.store_id in (".implode(',', $store_id_arr).") and c2.use_time = 0";
		
		$couponList = $Model->query($sql);
        // dump($Model->getLastSql());
        // dump($couponList);
		
		//如果已经使用过的优惠券做好标记
		$couponList_new=array();
		$new_key=0;
		$coupon_brand=0;
		$coupon_brand2=0;
		$goods_name_coupon = '';
        
		foreach($couponList  as $key=>$value){
			
			//判断入驻商家优惠券是否符合使用规则   by tianxin100
			if($value['store_id']){
				//查询当前购物车中输入这个店铺的商品总金额  by tianxin100
				$store_total_price=$this->cartLogic->cart_store_price($usersInfo, $unique_id, 1, $value['store_id']); // 获取购物车商品			
				if($value['condition']<$store_total_price){
					
					if($value['goods_ids']){
					    $cgoods_ids = json_decode($value['goods_ids'],true);
					    foreach ($goods_ids as $k=>$v){
                            if(!in_array($v,$cgoods_ids)){
                                $coupon_brand2 = 1;
                                // $goods_name_coupon .= $v['goods_name'];
                                break; // 如果只需要标记一次，可以跳出循环
                            }
                        }
                        if($coupon_brand2 == 0){
                            $couponList_new[$new_key]['type'] = 1;
                            $couponList_new[$new_key]['goods_name_coupon'] = '';
                        }else{
                            $couponList_new[$new_key]['type'] = 0;
                            $couponList_new[$new_key]['name'] = $value['name'].'(特定商品使用)';
                        }
					}
                  

					$couponList_new[$new_key]=$value;
					$couponList_new[$new_key]['use_start_time']=date("Y-m-d",$value['use_start_time']); 
					$couponList_new[$new_key]['use_end_time']=date("Y-m-d",$value['use_end_time']); 
					if(count($store_arr) > 1){
                        $couponList_new[$new_key]['type'] = 0;
                        $couponList_new[$new_key]['name'] = $value['name'].'(单一店铺使用)';
                    }
					if(!empty($value['use_time'])){
						$couponList_new[$new_key]['status']=1;
					}else{
						$couponList_new[$new_key]['status']=0;
					}
					$new_key++;
				}	
			}else{
                if($value['condition']<=$cart_result['total_price']['original_fee']){
                    
                    
                    if(!empty($value['brand_id'])){
                        $brand = json_decode($value['brand_id'],true);
                        /// 获取所有品牌名称
                        // $brandNames = $brand; // 因为 $brand 已经是品牌名称数组
                    
                        // 将品牌名称数组转换为 SQL 查询所需的格式
                        // $brandNamesForSQL = '"' . implode('","', $brandNames) . '"';
                    
                        // 获取所有品牌 ID
                        $brandList = M('brand')->where('id IN ('.implode(',',$brand).')')->getField('id', true);
                        
                        foreach ($cartList as $k=>$v){
                            // $a = $brandList;
                            // $tempBrandList = $brandList;
                            // $res = in_array($v['brand_id'],$tempBrandList);
                            if(!in_array($v['brand_id'],$brand)){
                                $coupon_brand = 1;
                                $goods_name_coupon .= $v['goods_name'];
                                // break; // 如果只需要标记一次，可以跳出循环
                            }
                            
                            //删除其他分类的优惠券
                        }
                        
                        if($coupon_brand == 0){
                            $value['type'] = 1;
                            $value['goods_name_coupon'] = '';
                        }else{
                            $value['type'] = 0;
                            $value['name'] = $value['name'].'(特定品牌使用)';
                        }
                        $couponList_new[$new_key]['store_name'] = '品牌优惠券';
                        $couponList_new[$new_key]=$value;
                        $couponList_new[$new_key]['use_start_time']=date("Y-m-d",$value['use_start_time']); 
                        $couponList_new[$new_key]['use_end_time']=date("Y-m-d",$value['use_end_time']); 
                        $couponList_new[$new_key]['status']=0;
                        $new_key++;
                    }else{
                        $value['type'] = 1;
                        $couponList_new[$new_key]['store_name'] = '全场通用';
                        $couponList_new[$new_key]=$value;
                        $couponList_new[$new_key]['use_start_time']=date("Y-m-d",$value['use_start_time']); 
                        $couponList_new[$new_key]['use_end_time']=date("Y-m-d",$value['use_end_time']); 
                        $couponList_new[$new_key]['status']=0;
                        $new_key++;
                    }
                    
                }
            }
			
		}
// 		if($coupon_brand == 1){
// 		    $couponList_new = [];
// 		}
        // 收货地址
        $addresslist = M('UserAddress')->where("user_id = {$this->user_id}")->select();
	if(!empty($addresslist)){
	        $c = M('UserAddress')->where("user_id = {$this->user_id} and is_default = 1")->count(); // 看看有没默认收货地址
	        if ((count($addresslist) > 0) && ($c == 0)){ // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
	            $addresslist[0]['is_default'] = 1;
			}
	        else if (count($addresslist) > 0) 
	        {
	            $addresslist[0] = M('UserAddress')->where("user_id = {$this->user_id} and is_default = 1")->find();
	        }
	        //计算运费 BY 维亚轩 小东 2018-04-11
			$shipping_fee = 0;
	        if (!empty($addresslist[0])) {
	            $shippingPrice = $this->cartLogic->cart_freight_mrlu($orderGoods,$addresslist[0]['province'],$addresslist[0]['city'],$addresslist[0]['district'],1000);
				$cart_result['total_price']['total_fee'] += $shippingPrice['total_shipping_fee'];
	        }
		$addresslist[0]['province']=M('region')->where(array("id"=>$addresslist[0]['province']))->getField('name');
		$addresslist[0]['city']=M('region')->where(array("id"=>$addresslist[0]['city']))->getField('name');
		$addresslist[0]['district']=M('region')->where(array("id"=>$addresslist[0]['district']))->getField('name');
	}else{
		$shippingPrice['total_shipping_fee'] = 0;
	}
    
        //选择优惠卷后计算
        $coupon_id =I("coupon_id",0); //  优惠券id
        $coupon_money = 0;
        if($coupon_id){
            $cid = M('coupon_list')->where(array("id"=>$coupon_id))->getField("cid");
            $coupon_money = M('coupon')->where(array("id"=>$cid))->getField("money");
        }
        $cart_result['total_price']['coupon_fee'] = sanwei($coupon_money);
        $cart_result['total_price']['total_fee'] -= sanwei($coupon_money);

        $cart_result['total_price']['coupon_fee'] = sanwei($cart_result['total_price']['coupon_fee']);
        $cart_result['total_price']['total_fee'] = sanwei($cart_result['total_price']['total_fee']);
        $points = M("config")->where(array("name"=>"point_rate"))->getField("value");
        $json_arr = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => array(
                'addressList' => $addresslist[0], // 收货地址
                //'shippingList' => $shippingList, //物流列表
                'cartList' => $cart_result['cartList'], // 购物车列表
                'totalPrice' => $cart_result['total_price'], // 总计
                'couponList' => $couponList_new, //优惠券列表
                'userInfo' => $usersInfo, // 用户详情
                "points"=>$points,
                "express_price"=>$shippingPrice['total_shipping_fee'],
				"paymentList"  =>$paymentList,
				"is_show_coupin"  =>$basic['is_show_coupin'],
				'goods_name_coupon'=>$goods_ids,
				'aa'=>count($store_arr)
            ));
        exit(json_encode($json_arr));
    }

    /**
     * 获取订单商品价格 或者提交 订单 
     */
    public function cart3()
    {
        $basic=tpCache("basic");
        if($basic['system_open'] == 0){
            exit(json_encode(array('status'=>-1,'msg'=>'系统关闭，无法下单','result'=>[])));
        }
		//exit(json_encode(array('status'=>-1,'msg'=>'我们平台即将开放，敬请期待，感谢支持！','result'=>null)));
        //$unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $this->user_id = I("user_id"); // 用户id
        $usersInfo = get_user_info($this->user_id);  // 用户
        $address_id = I("address_id"); //  收货地址id
        $shipping_code = array('tiantian'); //  物流编号
        $invoice_title = I('invoice_title',"苏州某公司"); // 发票
        $couponTypeSelect = array(1); //  优惠券类型  1 下拉框选择优惠券 2 输入框输入优惠券代码
        $coupon_id =I("coupon_id",0); //  优惠券id
        $couponCode = array(); //  优惠券代码
        $pay_points = I("pay_points", 0); //  使用积分
        $user_money = I("user_money", 0); //  使用余额
		$payment = I("pay_code"); //  支付方式
        $user_money = $user_money ? $user_money : 0;
        $user_note        = I('content');
        $spec_key        = I('spec_key','');
        // $user_note = I('user_note'); // 给卖家留言      数组形式
        
        $cv = $coupon_id;
        $coupon_array = [];
        $s_stored_id = M('coupon_list')->where(array("id"=>$cv))->getField("store_id");
        // if($s_stored_id)
        //     $coupon_array[$s_stored_id] = $cv;
        // else{
        	if($coupon_id) $coupon_array[0] = $cv;
        // } 
        $coupon_id = $coupon_array;

        if($spec_key){
            $spec_key2 = " and spec_key = '".$spec_key."' ";
        }
        if($spec_key){
            $spec_key = " and a.spec_key = '".$spec_key."' ";
        }

        if($this->cartLogic->cart_count($this->user_id,1) == 0 ) exit(json_encode(array('status'=>-1,'msg'=>'你的购物车没有选中商品','result'=>null))); // 返回结果状态
//        if(!$address_id) exit(json_encode(array('status'=>-1,'msg'=>'请完善收货人信息','result'=>null))); // 返回结果状态
        if(!$shipping_code) exit(json_encode(array('status'=>-1,'msg'=>'请选择物流信息','result'=>null))); // 返回结果状态
        
//        $address = M('UserAddress')->where("address_id = $address_id")->find();
		$order_goods = M('Cart')
		->alias('a')
		->field('a.*,b.is_on_sale,b.goods_state,b.points,b.stop_yijia,b.fenbu_koudian')
		->join('ty_goods b on a.goods_id=b.goods_id')
		->where("a.user_id = {$this->user_id} and a.selected = 1 and b.is_on_sale=1 and b.goods_state=1  ".$spec_key."")->select();
        //$order_goods = M('cart')->where("user_id = {$this->user_id} and selected = 1")->select();
	
        $result = calculate_price($this->user_id,$order_goods,$shipping_code,0,$address[province],$address[city],$address[district],$pay_points,$user_money,$coupon_id,$couponCode,$payment);  //echo \json_encode($result);exit;
        if($result['status'] < 0)
        	exit(json_encode($result));
        	$car_price = array(
        			'pay_name'      => $result['result']['pay_name'], // 支付方式
        			'postFee'      => $result['result']['shipping_price'], // 物流费
        			'couponFee'    => $result['result']['coupon_price'], // 优惠券
        			'balance'      => $result['result']['user_money'], // 使用用户余额
					'kou_price'    => $result['result']['kou_price'], // 使用用户余额
        			'pointsFee'    => $result['result']['integral_money'], // 积分支付
        			'payables'     => array_sum($result['result']['store_order_amount']), // 订单总额 减去 积分 减去余额
        			'goodsFee'     => $result['result']['goods_price'],// 总商品价格
					'yijia_heji'    => $result['result']['yijia_heji'], // 溢价合计
        			'order_prom_amount' => array_sum($result['result']['store_order_prom_amount']), // 总订单优惠活动优惠了多少钱
        			'store_order_prom_id'=> $result['result']['store_order_prom_id'], // 每个商家订单优惠活动的id号
        			'store_order_prom_amount'=> $result['result']['store_order_prom_amount'], // 每个商家订单活动优惠了多少钱
        			'store_order_amount' => $result['result']['store_order_amount'], // 每个商家订单优惠后多少钱, -- 应付金额
        			'store_shipping_price'=>$result['result']['store_shipping_price'],  //每个商家的物流费
        			'store_coupon_price'=>$result['result']['store_coupon_price'],  //每个商家的优惠券抵消金额
        			'store_point_count' => $result['result']['store_point_count'], // 每个商家平摊使用了多少积分
        			'store_balance'=>$result['result']['store_balance'], // 每个商家平摊用了多少余额
        			'store_goods_price'=>$result['result']['store_goods_price'], // 每个商家的商品总价
        	);
        	
        
        // 提交订单
        if ($_REQUEST['act'] == 'submit_order') {  //echo \json_encode($car_price);exit;

            if($usersInfo && !$usersInfo['biaoshi_xian']){
                exit(json_encode(array('status'=>-1,'msg'=>'您的线路还没设置，请联系客服设置','result'=>null)));
            }

            //检查店铺起拍价
            // foreach ($car_price['store_goods_price'] as $key => $value) {
            //     $store = M('store')->where(['store_id'=>$key])->find();


            //     if ((float)$value < (float)$store['starting_price'] ){
            //         exit(json_encode(array('status'=>-1,'msg'=>$store['store_name'].'起拍价'.$store['starting_price'].'未达标','result'=>null)));
            //     }

            // }
            //检查user今天是否有下单
            $todayStart = strtotime(date('Y-m-d'));  // 当天0点时间戳
            $todayEnd = strtotime($today . ' 17:00:00');        // 当天23:59:59
            foreach($car_price['store_order_amount'] as $k => $v)
        {
            $store = M('store')->where(['store_id'=>$k])->find();
            $user_store_order = M('order')->where(['user_id'=>$this->user_id,'order_status'=>['in',[0,1,2]],'add_time' => ['between', "$todayStart,$todayEnd"],'store_id'=>$k])->sum('total_amount');
            if(($user_store_order+$car_price['store_goods_price'][$k]) < (float)$store['starting_price']){
                exit(json_encode(array('status'=>-1,'msg'=>$store['store_name'].'起拍价'.$store['starting_price'].'未达标','result'=>[])));
            }
        }


            $level_quota = M('user_level')->where(['level_id'=>$usersInfo['level']])->getField('quota');

            $user_order = M('order')->where(['user_id'=>$this->user_id,'order_status'=>['in',[0,1,2]],'add_time' => ['between', "$todayStart,$todayEnd"]])->find();

            //当天第一笔单笔满足起送价条件的，后续下单的可以不做校验，下多少钱都行
            if($this->user_id != 31 && !$user_order && $level_quota > 0 && $car_price['goodsFee'] < $level_quota){
                $diff_price = $level_quota - $car_price['goodsFee'];
                exit(json_encode(array('status'=>-1,'msg'=>'提交订单失败，差'.$diff_price.'金额满足下单条件','result'=>[])));
            }

			$cartLists = M('Cart')
				->alias('a')
				->field('a.*,b.is_on_sale,b.goods_state,b.is_delete,b.prom_id,c.start_time,c.end_time,c.xiangou,c.goods_key,c.day_type,
				(select sum(goods_num) from ty_cart where user_id = a.user_id and goods_id=a.goods_id and selected = 1) as xiangous')
				->join('ty_goods b on a.goods_id=b.goods_id')
				->join('ty_prom_goods c on b.prom_id=c.id')
				->where("a.user_id = ".$this->user_id." and a.selected = 1 and b.is_on_sale=1 and b.is_delete=0 and b.goods_state=1 ".$spec_key." and c.end_time>=".\time())->select();

				foreach($cartLists as $v){
				    $store = M('store')->where(['store_id'=>$v['store_id']])->find();
				    if($store['store_state'] == 0){
				        	exit(json_encode(array('status'=>-1,'msg'=>'商家：'.$store['store_name'].' 已经打样，请删除他的商品继续下单','result'=>null)));
				    }
				    if($v['day_type'] == 0){
				        $pds=M('order_goods a') //判断订单是否有产品
					->join('ty_order b on a.order_id=b.order_id')
					->where('b.order_status in (0,1,2) and b.add_time<='.$v['end_time'].' and b.add_time>='.$v['start_time'].' and user_id='.$this->user_id.' and goods_id='.$v['goods_id'].' and spec_key="'.$v['spec_key'].'"')->sum('goods_num');
				    }elseif($v['day_type'] == 1){
				        $start = strtotime("today");
				        $end = $todayStartTimestamp+86399;
				        $pds=M('order_goods a') //判断订单是否有产品
					->join('ty_order b on a.order_id=b.order_id')
					->where('b.order_status in (0,1,2) and b.add_time<='.$start.' and b.add_time>='.$end.' and user_id='.$this->user_id.' and goods_id='.$v['goods_id'].' and spec_key="'.$v['spec_key'].'"')->sum('goods_num');
				    }
					
					$v['xiangous']=$v['xiangous']=='' ? 0 : $v['xiangous'];
                        
                        if(($pds+$v['xiangous'])>$v['xiangou'] && $v['xiangou']>0 && strpos($v['goods_key'],$v['spec_key']) !== false){
						    exit(json_encode(array('status'=>-1,'msg'=>$v['goods_name'].' 限购数量'.$v['xiangou'].'件！','result'=>null)));
						} 
                      
						

					
					//判断库存
					$pd_kucun=M('spec_goods_price')->where("goods_id = ".$v['goods_id']." and `key`='".$v['spec_key']."'")->getField('store_count');
					if($pd_kucun<$v['goods_num'])
					exit(json_encode(array('status'=>-1,'msg'=>$v['goods_name'].' 库存不足！','result'=>null)));
				}
//exit;
            // $smoe_sn = str_pad(mt_rand(1,99999),5,'0 ',STR_PAD_LEft);
            $smoe_sn = date('YmdHis').substr(microtime(), 2, 5).mt_rand(10000,99999);
            $result = $this->cartLogic->addOrder($this->user_id, $address_id, $shipping_code, $invoice_title, $coupon_id, $car_price,$user_note,$payment,$smoe_sn,$spec_key,$spec_key2); // 添加订单

            $order = M('order')->where(array("master_order_sn"=>$result['result']))->select();
//            $result['data'] = $this->getWXPayInfo($result['result']);
			//如果是选的货到付款，暂时不需要付款 by   shadow 
			if($payment=="cod"){
				$result['data']['pay_money']=0;
			}
            if($payment == 'weixin'){
                $result['data']['wdata'] = json_decode($this->getWXPayInfo($order)['payinfo'],true);
            }
            $result['order'] = $order; 
            exit(json_encode($result));
        }
        $return_arr = array('status' => 1, 'msg' => '计算成功', 'result' => $car_price); // 返回结果状态
        exit(json_encode($return_arr));
    }

    public function weixin_del()
    {
        $action = I("action"); //1支付成功，2支付失败
        $master_order_sn = \trim(I("master_order_sn"));
        $user_id = \trim(I("user_id"));

        $pd=M('users')->where('user_id='.$user_id)->find();$code=-100;
        if($pd){
            $master=M('order')->field('order_id')->where('master_order_sn='.$master_order_sn)->select();
            if($action=='1'){ //支付成功
                M('order')->where('master_order_sn='.$master_order_sn)->save([
                    'pay_status'=>1,'pay_time'=>\time()
                ]);
                // foreach($master as $v){ //清空购物车
                // 	$order_good=M('order_goods')->field('goods_id')->where('order_id='.$v['order_id'])->select();
                // 	foreach($order_good as $v)
                // 	M('Cart')->where("goods_id =".$v['goods_id']." and user_id = $user_id and selected = 1")->delete();
                // }
            }else{ //支付失败
                foreach($master as $v){
                    M('order_goods')->where('order_id='.$v['order_id'])->delete();
                }
                M('order')->where('master_order_sn='.$master_order_sn)->delete();
            }
            $code=200;
        }

        exit(json_encode(['status' =>$code, 'result' =>'ok'])); // 返回结果状态
    }
	
    public function getWXPayData()
    {
    	$order_id = $_GET['order_id'];
		//判断商品是否下架  下架后提示不能支付
        $orders = M('order')->where(array("master_order_sn"=>$order_id))->select();
		if(empty($orders)){
			
			$master_order_sn=M('order')->where(array("order_id"=>$order_id))->getField('master_order_sn');
			if($master_order_sn){
				$orders = M('order')->where(array("master_order_sn"=>$master_order_sn))->select();
			}
		}
		if($orders){
			foreach($orders  as $key=>$value){
				
				$goods = M('order_goods  as og')->join('ty_goods as g')->field('g.is_on_sale')->where('og.goods_id = g.goods_id and og.order_id='.$value['order_id'])->select();
				foreach($goods  as $key=>$value){
					
					if(empty($value['is_on_sale'])){
						
						$return_arr = array('status' => 0, 'msg' => '失败', 'result' => "商品下架了"); // 返回结果状态
						exit(json_encode($return_arr));
					}
				}
				
			}
		}
    	$return_arr = array('status' => 1, 'msg' => '成功', 'result' => $this->getWXPayInfo($order_id)); // 返回结果状态
    	exit(json_encode($return_arr));
    }

    public function getWXPayInfo($order){
        $order_id = [];
        foreach ($order as $key => $value) {
            $order_id[] = $value['order_id'];
        }
        $order_id = join(',',$order_id);
        $master_order_sn = get_order_sn();
        M('pay_merge_log')->add(['master_order_sn'=>$master_order_sn,'order_sn'=>$order_id,'add_time'=>date('Y-m-d H:i:s',time())]); //记录合并订单
        M('order')->where('order_id in ('.$order_id.')')->save(['pay_master_order_sn'=>$master_order_sn]);
        $pay = new PayController();
        $res = $pay->payApp($master_order_sn);
        return $res;
    }

    public function getWXPayInfo2($order_id)
    {
        $orders = M('order')->where(array("master_order_sn"=>$order_id))->select();
		if(empty($orders)){
			
			$master_order_sn=M('order')->where(array("order_id"=>$order_id))->getField('master_order_sn');
			if($master_order_sn){
				$orders = M('order')->where(array("master_order_sn"=>$master_order_sn))->select();
			}
		}

        $goods = M('order_goods')->where(array("order_id"=>$orders[0]['order_id']))->find();
        $orderBody = $goods['goods_name'];
        $tade_no =$orders[0]['master_order_sn'].get_rand_str(3,0);
        $user_id = $orders[0]['user_id'];
        $open_id = D('users')->where(array("user_id"=>$user_id))->getField("open_id");
        $total_fee = 0;
        foreach ($orders as $order)
            $total_fee += ($order['order_amount']+$order['yijia_heji']) * 100;


        $total_fee=round($total_fee);
        $data1 = [];
//        $kuPay = new PayController();
//        $response = $kuPay->kuPaySkippay($orderBody, $tade_no, $total_fee,$open_id);
////        print_r($response);exit;
////        $x = $response['pay_info'];;
//        //print_r($x);
//
//        $data1['wdata'] = $response;
//        $data1['pay_money'] = $total_fee;
        
        return $data1;
        //print_r($data1); // 返回新增的订单id
    }
   
    public function getPrePayOrder($body, $out_trade_no, $total_fee,$open_id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 
		
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/index.php/WXAPI/Pay/wxCallback';
        $onoce_str = $this->getRandChar(32);
    
        $data["appid"] = $config_value['appid'];
        $data["body"] = $body;
        $data["mch_id"] =$config_value['mchid'];
        $data["nonce_str"] = $onoce_str;
        $data["notify_url"] = $notify_url;
        $data["out_trade_no"] = $out_trade_no;
        $data["spbill_create_ip"] = $this->get_client_ip();
        $data["total_fee"] = $total_fee;
        $data["trade_type"] = "JSAPI";
        $data["openid"] = $open_id;
        $s = $this->getSign($data, false);
        $data["sign"] = $s;
    
        
        
        $xml = $this->arrayToXml($data);
        
        $response = $this->postXmlCurl($xml, $url);
    
        //echo $response;
        // 将微信返回的结果xml转成数组
        return $this->xmlstr_to_array($response);
    }
    
    // 执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 		
        $data["appId"] = $config_value['appid'];
        $data["nonceStr"] = $this->getRandChar(32);
        $data["package"] = "prepay_id=".$prepayId;
        $data['signType'] = "MD5";
        $data["timeStamp"] = time();
        //$data["partnerid"] = $this->config['mch_id'];
        //$data["prepayid"] = $prepayId;
        
        $s = $this->getSign1($data, false);
        $data["sign"] = $s;
        //$data["prepayid"] = $prepayId;
        return $data;
    }
    
    // 获取指定长度的随机字符串
    function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;
    
        for ($i = 0; $i < $length; $i ++) {
            $str .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
    
        return $str;
    }
    /*
     * 生成签名
     */
    function getSign($Obj)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 				
        foreach ($Obj as $k => $v) {
            $Parameters[strtolower($k)] = $v;
        }
        // 签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        // echo "【string】 =".$String."</br>";
        // 签名步骤二：在string后加入KEY
        $String = $String . "&key=" .  $config_value['key'];
        // echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
        // 签名步骤三：MD5加密
        $result_ = strtoupper(md5($String));
        return $result_;
    }
    
    /*
     * 生成签名
     */
    function getSign1($Obj)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 		
        foreach ($Obj as $k => $v) {
            $Parameters[strtolower($k)] = $v;
        }
        // 签名步骤一：按字典序排序参数
        ksort($Parameters);
        //$String = $this->formatBizQueryParaMap($Parameters, false);
        $String  = "appId=".$Obj['appId']."&nonceStr=".$Obj['nonceStr']."&package=".$Obj['package']."&signType=MD5&timeStamp=".$Obj['timeStamp']; 
        
        // echo "【string】 =".$String."</br>";
        // 签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $config_value['key'];
        // echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
        // 签名步骤三：MD5加密
        //echo $String;
        $result_ = strtoupper(md5($String));
        return $result_;
    }
    
    /*
     * 获取当前服务器的IP
     */
    function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }
    
    // 数组转xml
    function arrayToXml($arr)
    {
        
        $xml = "<xml>";
        
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        
        
        return $xml;
    }
    
    // post https请求，CURLOPT_POSTFIELDS xml格式
    function postXmlCurl($xml, $url, $second = 30)
    {
        // 初始化curl
        $ch = curl_init();
        // 超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        // 这里设置代理，如果有的话
        // curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        // curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        // 运行curl
        $data = curl_exec($ch);
        
        // 返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
                echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
                    curl_close($ch);
                    return false;
        }
    }
    
    /**
     * xml转成数组
     */
    function xmlstr_to_array($xmlstr)
    {
        //$doc = new \DOMDocument();
        //$doc->loadXML($xmlstr);
        //return $this->domnode_to_array($doc->documentElement);
        
        //禁止引用外部xml实体
        
        libxml_disable_entity_loader(true);
        
        $xmlstring = simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA);
        
        $val = json_decode(json_encode($xmlstring),true);
        
        return $val;
        
        
    }
    
    // 将数组转成uri字符串
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
    
    function domnode_to_array($node)
    {
        $output = array();
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
            case XML_ELEMENT_NODE:
                for ($i = 0, $m = $node->childNodes->length; $i < $m; $i ++) {
                    $child = $node->childNodes->item($i);
                    $v = $this->domnode_to_array($child);
                    if (isset($child->tagName)) {
                        $t = $child->tagName;
                        if (! isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    } elseif ($v) {
                        $output = (string) $v;
                    }
                }
                if (is_array($output)) {
                    if ($node->attributes->length) {
                        $a = array();
                        foreach ($node->attributes as $attrName => $attrNode) {
                            $a[$attrName] = (string) $attrNode->value;
                        }
                        $output['@attributes'] = $a;
                    }
                    foreach ($output as $t => $v) {
                        if (is_array($v) && count($v) == 1 && $t != '@attributes') {
                            $output[$t] = $v[0];
                        }
                    }
                }
                break;
        }
        return $output;
    }
    
    
}
